#include <QVBoxLayout>
#include <QListWidget>
#include <data_display/totplistwidget.h>
#include "data_display/totpitemwidget.h"

namespace data_display {
TOTPListWidget::TOTPListWidget(utils::ClipboardWatcher &clipboard_watcher, QWidget *parent): QWidget(parent),
				_clipboard_watcher(clipboard_watcher) {
	setWindowTitle("список TOTP");

	auto *layout = new QVBoxLayout(this);

	totpListWidget = new QListWidget(this);
	layout->addWidget(totpListWidget);

	setLayout(layout);
	connect(totpListWidget, SIGNAL(itemClicked(QListWidgetItem *)), this, SLOT(copyTOTPToClipboard(QListWidgetItem *)));

}

void TOTPListWidget::onTOTPDeleteRequested(const totp::TOTP &totp) {
	for (int i = 0; i < totpListWidget->count(); ++i) {
		QListWidgetItem *item = totpListWidget->item(i);
		auto *widget = qobject_cast<TOTPItemWidget*>(totpListWidget->itemWidget(item));
		if (widget && widget->getTOTP().label == totp.label) {
			delete totpListWidget->takeItem(i); // Удаляем элемент из списка
			emit totpDeleted(totp); // Отправляем сигнал на удаление в TOTPWindow
			break;
		}
	}
}

void TOTPListWidget::copyTOTPToClipboard(QListWidgetItem *item) {
	if (auto *widget = qobject_cast<TOTPItemWidget*>(totpListWidget->itemWidget(item))) {
		_clipboard_watcher.setClipboardData(widget->getPasswrodLabel());
		emit PasswordCopied();
	}
}

void TOTPListWidget::copyTOTPToClipboard(const QString& password) {
	if (not password.isEmpty()) {
		_clipboard_watcher.setClipboardData(password);
		emit PasswordCopied();
	}
}

void TOTPListWidget::addTOTP(const totp::TOTP &totp) {
	auto itemWidget = new TOTPItemWidget(totp);

	auto *item = new QListWidgetItem();
	connect(itemWidget, SIGNAL(passwordCopied(QString)), this, SLOT(copyTOTPToClipboard(QString)));
	connect(itemWidget, &TOTPItemWidget::deleteRequested, this, &TOTPListWidget::onTOTPDeleteRequested);
	item->setSizeHint(itemWidget->sizeHint());
	totpListWidget->addItem(item);
	totpListWidget->setItemWidget(item, itemWidget);
}
}
